package global

import (
	"github.com/spf13/viper"
	"sync"
)

type Global interface {
	Get()
}

type ConnInfo struct {
	//自增ID 全局唯一，每个用户建立ws链接 +1
	Id   int64
	name string
	// 全局所有在线用户信息 ，考虑到一个用户会有多个终端登录，用数组记录，数组里记录的是用链接id 对应ConnList里面的key
	UserList map[string][]string
	// 全局房间信息
	RoomList map[string]map[string]string
	//key 是ip	记录token错误 次数
	FailToken map[string]FailToken
	//	 viper.GetString("auth.tokenIpWhitelist.ip")
	//ip 白名单
	IpWhitelist []string
	//黑名单配置
	IpBlacklistCfg IpBlacklistCfg
	mutex          sync.RWMutex
}

func (this *ConnInfo) GetUserList() map[string][]string {
	defer this.mutex.Unlock()
	this.mutex.Lock()
	return this.UserList
}
func (this *ConnInfo) GetUserListVal(key string) []string {
	defer this.mutex.Unlock()
	this.mutex.Lock()
	return this.UserList[key]
}

func (this *ConnInfo) UpdateUserList(key string, value []string) {
	this.mutex.Lock()
	defer this.mutex.Unlock()
	this.UserList[key] = value
}

func (this *ConnInfo) DelUserList(key string, connId string) {
	defer this.mutex.Unlock()
	this.mutex.Lock()
	if this.UserList[key] != nil {
		var users = this.UserList[key]
		if connId != "" && len(users) > 0 {
			for index, cid := range users {
				if cid == connId {
					this.UserList[key] = append(users[:index], users[index+1:]...)
				}
			}
		}
		if len(this.UserList[key]) == 0 || connId == "" {
			delete(this.UserList, key)
		}
	}
}
func (this *ConnInfo) GeRoomList() map[string]map[string]string {
	defer this.mutex.Unlock()
	this.mutex.Lock()
	return this.RoomList
}
func (this *ConnInfo) GetRoomListVal(key string) map[string]string {
	defer this.mutex.Unlock()
	this.mutex.Lock()
	return this.RoomList[key]
}

func (this *ConnInfo) UpdateRoomList(key string, value map[string]string) {
	this.mutex.Lock()
	defer this.mutex.Unlock()
	this.RoomList[key] = value
}

func (this *ConnInfo) DelRoomList(key string, connId string) {
	defer this.mutex.Unlock()
	this.mutex.Lock()
	if connId != "" && this.RoomList[key] != nil {
		if this.RoomList[key][connId] != "" {
			delete(this.RoomList[key], connId)
		}
	}
	if this.RoomList[key] != nil && len(this.RoomList[key]) == 0 {
		delete(this.RoomList, key)
	}
}

func NewConnInfo() *ConnInfo {
	connInfo_ := new(ConnInfo)
	connInfo_.Id = 1
	connInfo_.name = "myGlobal"
	//ws在线链接对应的用户数据
	connInfo_.UserList = make(map[string][]string)
	connInfo_.RoomList = make(map[string]map[string]string)
	//ipws鉴权失败缓存记录
	connInfo_.FailToken = make(map[string]FailToken)
	//IP 白名单
	connInfo_.IpWhitelist = viper.GetStringSlice("auth.ipWhitelist.ip")
	//ip黑名单配置
	connInfo_.IpBlacklistCfg = IpBlacklistCfg{viper.GetInt("auth.ipBlacklist.fail-max-num"), viper.GetInt64("auth.ipBlacklist.fail-interval-time")}
	return connInfo_
}
